package com.tutor.syslib.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Base64;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;

import static android.R.attr.path;

/**
 * Created by zzgpc on 2017-9-24.
 */

public class FileUtils {
    /**
     * 获取缓存文件夹位置
     *
     * @return
     */
    public static File getExternalCacheFile(Context context) {
        return context.getExternalCacheDir();
    }


    public static String getCacheFileLength(ArrayList<File> cacheFileList) {

        float f = 0;
        long totalSize = 0;
        DecimalFormat df = new DecimalFormat("###.##");
        for (File cacheFile : cacheFileList) {
            File[] fileList = cacheFile.listFiles();
            for (File temp : fileList) {
                totalSize += temp.length();
            }
            f = ((float) totalSize / (float) (1024 * 1024));
        }

        // 以下代码返回的是带kb的
//        if (f < 1.0) {
//            float f2 = ((float) totalSize / (float) (1024));
//            return df.format(new Float(f2).doubleValue()) + "KB";
//
//        } else {
//            return df.format(new Float(f).doubleValue()) + "M";
//        }
        // 以下代码返回的是纯M的
        return df.format(new Float(f).doubleValue()) + "M";

    }

    /**
     * 获取app
     * 根目录
     *
     * @return String
     * @throws
     * @since 1.0.0
     */
    public static String getAppPath() {

        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
//        File cacheDir = NewQSHealthApplication.applicationContext.getFilesDir();//文件所在目录为getFilesDir();android/data/com.winning.newchealthchat/
//        String cachePath = cacheDir.getPath();
//        String kxPath = sdDir.getAbsolutePath() + "/HealthChat";
//        String kxPath = cacheDir.getAbsolutePath() + "/HealthChat";
        File kxFile = new File(sdDir, "dingNing");
        if (!kxFile.exists()) {
            kxFile.mkdirs();
        }
        return kxFile.getAbsolutePath();

    }

    /**
     * 压缩且保存图片到fileName
     *
     * @param rawBitmap
     * @param fileName
     */
    public static void compressAndSaveBitmapToFile(Bitmap rawBitmap,
                                                   String fileName, int quality) {
//        String saveFilePaht = this.getSDCardPath() + File.separator + fileName;
        File saveFile = new File(fileName);
        saveFile.delete();
        if (!saveFile.exists()) {
            try {
                saveFile.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(
                        saveFile);
                if (fileOutputStream != null) {
                    // imageBitmap.compress(format, quality, stream);
                    // 把位图的压缩信息写入到一个指定的输出流中
                    // 第一个参数format为压缩的格式
                    // 第二个参数quality为图像压缩比的值,0-100.0 意味着小尺寸压缩,100意味着高质量压缩
                    // 第三个参数stream为输出流
                    rawBitmap.compress(Bitmap.CompressFormat.JPEG, quality,
                            fileOutputStream);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }

    public static byte[] File2byte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }


    /**
     * 将文件io流读写为字符串
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String readFileContent(String fileName) throws IOException {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {

            InputStream in = new FileInputStream(fileName);

            data = new byte[in.available()];

            in.read(data);

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return Base64.encodeToString(data, Base64.DEFAULT);
////        Base64 encoder = new BASE64Encoder();
//        // 返回Base64编码过的字节数组字符串
//        return encoder.encode(data);


//        File file = new File(fileName);
//        if (!file.exists()) {
//            return null;
//        }
//
//        BufferedReader bf = new BufferedReader(new FileReader(file));
//
//        String content = "";
//        StringBuilder sb = new StringBuilder();
//
//        while (content != null) {
//            content = bf.readLine();
//
//            if (content == null) {
//                break;
//            }
//
//            sb.append(content.trim());
//        }
//
//        bf.close();
//        return sb.toString();
    }


    /**
     * InputStream 转化为string
     *
     * @param is
     * @return
     */
    public static String inputStreamToStr(InputStream is) {
        String str;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            str = baos.toString();
        } catch (IOException e) {
            return null;
        }

        return str;
    }
}
